<template>
  <div class="supplier-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>供应商管理</h2>
    </div>

    <!-- 调试信息
    <div v-if="showDebugInfo" class="debug-info"
      style="background: #f0f9ff; border: 1px solid #0ea5e9; padding: 10px; margin-bottom: 10px; border-radius: 4px;">
      <div style="color: #0369a1; font-weight: bold;">🔧 调试信息</div>
      <div>供应商数据: {{ supplierList.length }} 条</div>
      <div>API状态: {{ apiStatus }}</div>
      <div v-if="debugMessage">{{ debugMessage }}</div>
      <div v-if="lastError" style="color: #dc2626;">❌ 最后错误: {{ lastError }}</div>
      <div>数据字典状态:</div>
      <div>- 供应商等级: {{ dataDictionary.supplierLevels.length }} 条</div>
      <div>- 供应商类别: {{ dataDictionary.supplierCategories.length }} 条</div>
      <div>- 业务性质: {{ dataDictionary.businessNatures.length }} 条</div>
      <div>- 行业: {{ dataDictionary.industries.length }} 条</div>
      <div>- 地区: {{ dataDictionary.locations.length }} 条</div>
      <div>- 人员: {{ dataDictionary.people.length }} 条</div>
      <div>当前选中的供应商: {{ currentSupplier ? currentSupplier.supplierName : '无' }}</div>
      <div>对话框状态: {{ dialogVisible ? '打开' : '关闭' }} ({{ dialogMode }})</div>
      <div>详情对话框状态: {{ detailDialogVisible ? '打开' : '关闭' }}</div>
      <div style="margin-top: 10px;">

      </div>
    </div> -->

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="left-actions">
        <el-button type="primary" @click="handleAdd" :icon="Plus">新增</el-button>
        <el-button @click="handleImport" :icon="Upload">导入</el-button>
        <el-button @click="toggleDebugInfo" type="info" size="small">
          {{ showDebugInfo ? '隐藏调试' : '显示调试' }}
        </el-button>
        <el-button @click="testApiConnection" type="success" size="small">
          测试API连接
        </el-button>
        <el-button @click="testAllApis" type="success" size="small">
          测试所有API
        </el-button>
        <el-button @click="loadSupplierList" type="primary" size="small">
          重新加载
        </el-button>
      </div>
      <div class="right-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="请搜索"
          style="width: 300px"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" :icon="Search"></el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 供应商列表 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="supplierList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="serialNumber" label="序号" width="80" />
        <el-table-column prop="supplierNumber" label="供应商编号" width="150" />
        <el-table-column prop="supplierName" label="供应商名称" width="200" />
        <el-table-column prop="companyName" label="公司名称" width="200" />
        <el-table-column prop="supplierCategoryName" label="供应商类别" width="120" />
        <el-table-column prop="supplierLevelName" label="供应商等级" width="120" />
        <el-table-column prop="industryName" label="所属行业" width="120" />
        <el-table-column prop="locationName" label="所在地区" width="120" />
        <el-table-column prop="purchaseRepresentativeName" label="采购人员" width="120" />
        <el-table-column prop="isEnabled" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isEnabled ? 'success' : 'danger'">
              {{ scope.row.isEnabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="info" size="small" @click="handleView(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[4, 6, 8, 12]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <SupplierDialog
      v-model="dialogVisible"
      :mode="dialogMode"
      :supplier="currentSupplier"
      @success="handleDialogSuccess"
    />



    <!-- 详情对话框 -->
    <SupplierDetailDialog
      v-model="detailDialogVisible"
      :supplier="currentSupplier"
      @edit="handleEditFromDetail"
      @delete="handleDeleteFromDetail"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Search } from '@element-plus/icons-vue'
import SupplierDialog from './components/SupplierDialog.vue'
import SupplierDetailDialog from './components/SupplierDetailDialog.vue'
import { getErrorMessage, isNetworkError } from '@/utils/error'
import {
  getSupplierList,
  deleteSupplier,
  getAllSupplierLevels,
  getAllSupplierCategories,
  getAllBusinessNatures,
  getAllIndustries,
  getAllLocations,
  getAllPersons,
  getSupplierById
} from '@/Https/server'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const currentSupplier = ref<any>(null)
const selectedSuppliers = ref<any[]>([])
const supplierList = ref<any[]>([])

// 数据字典缓存
const dataDictionary = ref({
  supplierLevels: [],
  supplierCategories: [],
  businessNatures: [],
  industries: [],
  locations: [],
  people: []
})

// 调试信息
const showDebugInfo = ref(true) // 默认显示调试信息
const debugMessage = ref('')
const lastError = ref('')
const apiStatus = ref('')

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 4,
  total: 0
})

// 计算属性
const serialNumber = computed(() => {
  return (index: number) => {
    if (typeof index !== 'number' || index < 0) {
      return 1
    }
    return (pagination.currentPage - 1) * pagination.pageSize + index + 1
  }
})

// 加载数据字典（不使用，直接置空以避免报错）
const loadDataDictionary = async () => {
  dataDictionary.value = {
    supplierLevels: [],
    supplierCategories: [],
    businessNatures: [],
    industries: [],
    locations: [],
    people: []
  } as any
  debugMessage.value = '已跳过数据字典加载（使用真实数据）'
}

// 方法
const loadSupplierList = async (retryCount = 0) => {
  try {
    loading.value = true
    debugMessage.value = '正在加载供应商列表...'
    lastError.value = ''
    
    // 修复参数格式，确保与后端API匹配
    const params = {
      pageIndex: pagination.currentPage,  // 改为小写开头
      pageSize: pagination.pageSize,      // 改为小写开头
      keyword: searchKeyword.value || ''  // 确保keyword不为undefined
    }
    
    console.log('请求供应商列表参数:', params)
    
    // 添加参数验证
    if (params.pageIndex < 1) {
      params.pageIndex = 1
    }
    if (params.pageSize < 1) {
      params.pageSize = 4
    }
    
    const response = await getSupplierList(params)
    console.log('供应商列表API响应:', response)
    
    if (response.success) {
      const data = response.data
      console.log('供应商列表原始数据:', data)
      
      // 简化数据处理逻辑
      let suppliers = []
      let totalCount = 0
      
      if (data && typeof data === 'object') {
        // 尝试多种可能的数据结构
        if (data.pageData && Array.isArray(data.pageData)) {
          suppliers = data.pageData
          totalCount = data.totalCount || 0
        } else if (data.PageData && Array.isArray(data.PageData)) {
          suppliers = data.PageData
          totalCount = data.TotalCount || 0
        } else if (data.Data && Array.isArray(data.Data)) {
          suppliers = data.Data
          totalCount = data.totalCount || data.TotalCount || 0
        } else if (Array.isArray(data)) {
          suppliers = data
          totalCount = data.length
        }
      }
      
      // 验证数据有效性
      if (!Array.isArray(suppliers)) {
        console.warn('供应商数据格式无效:', suppliers)
        suppliers = []
        totalCount = 0
      }
      
      // 设置供应商列表
      supplierList.value = suppliers
      pagination.total = totalCount
      
      // 添加序号
      supplierList.value.forEach((item: any, index: number) => {
        if (item) {
          item.serialNumber = serialNumber.value(index)
        }
      })

      console.log('最终供应商列表数据:', supplierList.value)

      // 更新调试信息
      if (suppliers.length > 0) {
        debugMessage.value = `数据加载完成: ${suppliers.length} 条供应商数据，总数: ${totalCount}`
        apiStatus.value = '数据加载成功'
      } else {
        debugMessage.value = '数据加载完成，但没有供应商数据'
        apiStatus.value = '数据为空'
        lastError.value = '没有找到供应商数据，请检查数据库或添加测试数据'
      }
      
      lastError.value = ''
    } else {
      const errorMsg = response.message || '获取供应商列表失败'
      console.error('供应商列表API返回失败:', errorMsg)
      
      // 如果是网络错误且重试次数少于3次，则重试
      if (retryCount < 3 && (errorMsg.includes('网络') || errorMsg.includes('连接'))) {
        console.log(`第${retryCount + 1}次重试...`)
        setTimeout(() => {
          loadSupplierList(retryCount + 1)
        }, 1000 * (retryCount + 1)) // 递增延迟
        return
      }
      
      ElMessage.error(errorMsg)
      lastError.value = errorMsg
      apiStatus.value = 'API调用失败'
      
      // 清空数据
      supplierList.value = []
      pagination.total = 0
    }
  } catch (error: unknown) {
    console.error('加载供应商列表失败:', error)
    const errorMsg = getErrorMessage(error) || '加载供应商列表失败'
    
    // 如果是网络错误且重试次数少于3次，则重试
    if (retryCount < 3 && isNetworkError(error)) {
      console.log(`第${retryCount + 1}次重试...`)
      setTimeout(() => {
        loadSupplierList(retryCount + 1)
      }, 1000 * (retryCount + 1))
      return
    }
    
    ElMessage.error(errorMsg)
    lastError.value = errorMsg
    apiStatus.value = '加载失败'
    
    // 清空数据
    supplierList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadSupplierList()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadSupplierList()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  loadSupplierList()
}

const handleSelectionChange = (selection: any[]) => {
  selectedSuppliers.value = selection
}

const handleAdd = () => {
  console.log('新增按钮被点击')
    dialogMode.value = 'add'
    currentSupplier.value = null
    dialogVisible.value = true
    console.log('对话框状态:', dialogVisible.value, '模式:', dialogMode.value)
}

const handleEdit = async (row: any) => {
  console.log('编辑按钮被点击，行数据:', row)
  
  if (!row || !row.id) {
    console.error('无效的行数据:', row)
    ElMessage.error('无效的供应商数据')
    return
  }

  try {
    const detailResp = await getSupplierById(row.id)
    if (detailResp?.success && detailResp.data) {
      currentSupplier.value = detailResp.data
    } else {
      currentSupplier.value = { ...row }
    }
  } catch (e) {
    currentSupplier.value = { ...row }
  }

  dialogMode.value = 'edit'
  dialogVisible.value = true
  console.log('对话框状态:', dialogVisible.value, '模式:', dialogMode.value, '当前供应商:', currentSupplier.value)
}

const handleDelete = async (row: any) => {
  // 验证行数据的有效性
  if (!row || !row.id) {
    console.error('无效的行数据:', row)
    ElMessage.error('无效的供应商数据')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除供应商"${row.supplierName || '未知'}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteSupplier({ id: row.id })
    
    if (response.success) {
      ElMessage.success('删除成功')
      loadSupplierList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除供应商失败:', error)
      ElMessage.error('删除供应商失败')
    }
  }
}

const handleView = async (row: any) => {
  if (!row || !row.id) {
    console.error('无效的行数据:', row)
    ElMessage.error('无效的供应商数据')
    return
  }

  try {
    const resp = await getSupplierById(row.id)
    if (resp?.success && resp.data) {
      currentSupplier.value = resp.data
    } else {
      currentSupplier.value = { ...row }
    }
  } catch (e) {
    currentSupplier.value = { ...row }
  }

  detailDialogVisible.value = true
}

const handleImport = () => {
  ElMessage.info('导入功能待实现')
}

const handleDialogSuccess = () => {
  dialogVisible.value = false
  loadSupplierList()
}

const toggleDebugInfo = () => {
  showDebugInfo.value = !showDebugInfo.value
  if (showDebugInfo.value) {
    debugMessage.value = '调试信息已显示'
  } else {
    debugMessage.value = ''
  }
}

const testApiConnection = async () => {
  try {
    debugMessage.value = '正在测试API连接...'
    lastError.value = ''
    
    // 简单的API连接测试
    const testUrl = 'http://localhost:5000/api/Supplier/list'
    debugMessage.value = `正在测试仓库管理API: ${testUrl}`
    
    // 使用fetch进行简单的连接测试
    const response = await fetch(testUrl, { method: 'GET' })
    
    if (response.ok) {
      debugMessage.value = 'API连接测试成功！'
      apiStatus.value = 'API连接正常'
      ElMessage.success('API连接测试成功！')
      
      // 如果API连接正常，尝试重新加载数据
      setTimeout(async () => {
        await loadSupplierList()
      }, 1000)
      
    } else {
      debugMessage.value = `API连接测试失败: HTTP ${response.status}`
      apiStatus.value = 'API连接异常'
      lastError.value = `HTTP状态码: ${response.status}`
      ElMessage.warning('API连接测试失败')
    }
  } catch (error: unknown) {
    console.error('测试API连接失败:', error)
    const msg = getErrorMessage(error)
    debugMessage.value = `测试API连接失败: ${msg || '未知错误'}`
    lastError.value = `测试API连接失败: ${msg || '未知错误'}`
    apiStatus.value = '测试异常'
    ElMessage.error(`测试API连接失败: ${msg || '未知错误'}`)
  }
}

// 测试所有API连接
const testAllApis = async () => {
  try {
    debugMessage.value = '正在测试所有API连接...'
    lastError.value = ''
    
    // 测试主要的API端点
    const apis = [
      { name: '供应商列表', url: 'http://localhost:5000/api/Supplier/list' },
      { name: '供应商等级', url: 'http://localhost:5000/api/BusinessPartnerLevel/list' },
      { name: '供应商类别', url: 'http://localhost:5000/api/BusinessPartnerCategory/list' }
    ]
    
    let successCount = 0
    const results = []
    
    for (const api of apis) {
      try {
        const response = await fetch(api.url, { method: 'GET' })
        const success = response.ok
        if (success) successCount++
        
        results.push({
          name: api.name,
          success,
          status: response.status,
          url: api.url
        })
      } catch (error: unknown) {
        results.push({
          name: api.name,
          success: false,
          error: getErrorMessage(error),
          url: api.url
        })
      }
    }
    
    if (successCount === apis.length) {
      debugMessage.value = `所有API连接测试成功！共 ${apis.length} 个API`
      apiStatus.value = '所有API连接正常'
      ElMessage.success('所有API连接测试成功！')
      
      // 如果所有API都正常，尝试重新加载数据
      setTimeout(async () => {
        await loadSupplierList()
      }, 1000)
      
    } else {
      debugMessage.value = `API连接测试完成: ${successCount}/${apis.length} 个API正常`
      apiStatus.value = `部分API异常 (${successCount}/${apis.length})`
      
      // 显示失败的API
      const failedApis = results.filter(api => !api.success)
      if (failedApis.length > 0) {
        const failedNames = failedApis.map(api => api.name).join(', ')
        lastError.value = `异常的API: ${failedNames}`
        ElMessage.warning(`API连接测试完成，${failedApis.length} 个API异常`)
      }
      
      console.log('所有API连接测试结果:', results)
    }
  } catch (error: unknown) {
    console.error('测试所有API连接失败:', error)
    const msg = getErrorMessage(error)
    debugMessage.value = `测试所有API连接失败: ${msg || '未知错误'}`
    lastError.value = `测试所有API连接失败: ${msg || '未知错误'}`
    apiStatus.value = '测试异常'
    ElMessage.error(`测试所有API连接失败: ${msg || '未知错误'}`)
  }
}

const handleEditFromDetail = (supplier: any) => {
  console.log('从详情页面编辑供应商:', supplier)
  dialogMode.value = 'edit'
  currentSupplier.value = { ...supplier }
  dialogVisible.value = true
}

const handleDeleteFromDetail = (supplier: any) => {
  console.log('从详情页面删除供应商:', supplier)
  handleDelete(supplier)
}



// 生命周期
onMounted(async () => {
  console.log('供应商管理页面已挂载，开始加载数据...')
  
  try {
    // 先加载数据字典，再加载供应商列表
    await loadDataDictionary()
    await loadSupplierList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
})
</script>

<style scoped>
.supplier-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.left-actions {
  display: flex;
  gap: 12px;
}

.right-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.debug-info {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  background-color: #f0f9ff;
  border: 1px solid #0ea5e9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.debug-info div {
  margin-bottom: 5px;
}

.debug-info .el-tag {
  margin-right: 5px;
}
</style>